package com.mingtu.jgspatrol.fragment;

import static com.mingtu.jgspatrol.utils.MyConstant.ItemDecorationSpaces;
import static com.mingtu.jgspatrol.utils.MyConstant.animationType;
import static com.mingtu.jgspatrol.utils.MyConstant.isFirstOnly;
import static com.mingtu.jgspatrol.utils.MyConstant.isOpenLoadAnimation;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseBindingFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.decoration.LRSpaceItemDecoration;
import com.mingtu.common.decoration.TopSpaceItemDecoration;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.GridSpacingItemDecoration;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.ScreenUtils;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.activity.IndexFireDetails1Activity;
import com.mingtu.jgspatrol.activity.IndexFireDetails2Activity;
import com.mingtu.jgspatrol.adapter.FireNoticeAdapter;
import com.mingtu.jgspatrol.bean.IndexFireBean;
import com.mingtu.jgspatrol.databinding.FragmentFireNoticeBinding;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.mingtu.jgspatrol.utils.MySPTools;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;

public class FireNoticeFragment extends BaseBindingFragment<FragmentFireNoticeBinding> implements LazyFragmentPagerAdapter.Laziable {
    private int currentPage = 1;
    private boolean isLoadMore = true;
    private FireNoticeAdapter fireNoticeAdapter;
    private static final String ARG_PARAM1 = "param1";
    private int status = 0;

    public static FireNoticeFragment getInstance(int status) {
        FireNoticeFragment fragment = new FireNoticeFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ARG_PARAM1, status);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            status = getArguments().getInt(ARG_PARAM1);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_fire_notice;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        if (ScreenUtils.isTablet()) {
            GridLayoutManager manager1 = new GridLayoutManager(context, 2);
            binding.recycler.setLayoutManager(manager1);
            binding.recycler.addItemDecoration(new GridSpacingItemDecoration(2, SizeUtils.dp2px(ItemDecorationSpaces), true));
        } else {
            LinearLayoutManager manager1 = new LinearLayoutManager(context);
            binding.recycler.setLayoutManager(manager1);
            binding.recycler.addItemDecoration(new TopSpaceItemDecoration());
            binding.recycler.addItemDecoration(new BottomSpaceItemDecoration());
            binding.recycler.addItemDecoration(new LRSpaceItemDecoration());
        }
        fireNoticeAdapter = new FireNoticeAdapter(context);

        if (isOpenLoadAnimation) {
            fireNoticeAdapter.isFirstOnly(isFirstOnly);
            fireNoticeAdapter.openLoadAnimation(animationType);
        }

        fireNoticeAdapter.setEmptyView(new EmptyDataLayout(context));

        binding.recycler.setAdapter(fireNoticeAdapter);
        fireNoticeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                IndexFireBean.PageBean.ListBean listBean = fireNoticeAdapter.getData().get(position);
                String id = listBean.getId();
                String lnglat = listBean.getLnglat();
                String lngStr = "";
                String latStr = "";
                if (!StringUtils.isEmpty(lnglat)) {
                    if (lnglat.indexOf(",") != -1) {
                        String[] lnglatArray = lnglat.split(",");
                        lngStr = lnglatArray[0];
                        latStr = lnglatArray[1];
                    }
                }

                Bundle bundle = new Bundle();
                bundle.putString("fireId", id);
                if (status == 0) {
                    bundle.putString("lng", lngStr);
                    bundle.putString("lat", latStr);
                    IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), IndexFireDetails1Activity.class, bundle);
                } else if (status == 1) {
                    bundle.putString("title", "处理中火情");
                    IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), IndexFireDetails2Activity.class, bundle);
                } else if (status == 2) {
                    bundle.putString("title", "已处理火情");
                    IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), IndexFireDetails2Activity.class, bundle);
                }
            }
        });
    }

    @Override
    protected void getData() {
        initListener();
        getFireNoticetList(1);
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        binding.srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.srlUp.finishRefresh(Constant.REFRESH_TIME);
                binding.srlUp.setNoMoreData(false);
                currentPage = 1;
                getFireNoticetList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        binding.srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(fireNoticeAdapter.getData(), Constant.PAGE_SIZE);
                    getFireNoticetList(currentPage);
                }
                binding.srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 超时的督办工作列表
     */
    private void getFireNoticetList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        String beginTime = SPStaticUtils.getString(MySPTools.fireNoticeFliteBeginTime);
        String endTime = SPStaticUtils.getString(MySPTools.fireNoticeFliteEndTime);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        hashMap.put("beginTime", beginTime);
        hashMap.put("endTime", endTime);
        hashMap.put("status", status);

        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_INDEX_FIRE_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                IndexFireBean indexFireBean = new IndexFireBean();
                                indexFireBean = gson.fromJson(result, IndexFireBean.class);
                                List<IndexFireBean.PageBean.ListBean> dataBeans = indexFireBean.getPage().getList();

                                try {
                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            fireNoticeAdapter.replaceData(dataBeans);
                                        } else {
                                            fireNoticeAdapter.addData(dataBeans);
                                        }
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }


                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }
                        }
                    }
                });
    }

    /**
     * 筛选数据
     */
    public void filtJob() {
        getFireNoticetList(1);
    }

    /**
     * 重置数据
     */
    public void resetData() {
        getFireNoticetList(1);
    }

}